import { App, getCurrentInstance, Plugin } from "vue";
import { _RouteLocationBase, Router } from "vue-router";
import PageCacheUtil from "../utils/PageCacheUtil";

export function usePageCache() {
  const instance = getCurrentInstance();
  return instance.appContext.config.globalProperties.$pageCache;
}

/** 页面缓存插件 */
export default <Plugin<any[]>>{
  install: function (app: App) {
    const $bus = app.config.globalProperties.$bus;
    const $router: Router = app.config.globalProperties.$router;

    const pageCacheUtil = new PageCacheUtil();
    app.config.globalProperties.$pageCache = pageCacheUtil;

    $router.beforeEach(route => {
      pageCacheUtil.onRouterChange(route);
      $bus.emit('cacheKeysChange', pageCacheUtil.cacheKeys);
    });
  }
}

declare module "vue-router" {
  interface RouteMeta {
    cacheKey?: MetaFuncValue;
  }
}

declare module "@vue/runtime-core" {
  interface ComponentCustomProperties {
    $pageCache: PageCacheUtil;
  }
}
